/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
export var kthSmallest = function (root, k) {
  const stack = []
  dfs(root, k, stack)
  return stack.pop()
}

// 中序历遍便可
function dfs(node, k, stack = []) {
  if (!node) return false
  if (dfs(node.left, k, stack)) return true
  stack.push(node.val)
  if (stack.length === k) return true
  if (dfs(node.right, k, stack)) return true
  return false
}
